package com.awenhui.demo.dao;

import com.awenhui.demo.core.utils.HumpUtils;
import org.apache.ibatis.jdbc.SQL;

import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;

/**
 * @author yuxf
 * @version 1.0
 * @date 2021/2/23 18:00
 */
public class SuperSqlProvider {

    /**
     * 相等条件查询
     *
     * @param obj
     * @return
     */
    public String select(Object obj) throws IllegalAccessException {
        SQL sql = new SQL();
        Class<?> clazz = obj.getClass();
        String tableName;
        Table table = clazz.getAnnotation(Table.class);
        if (table != null) {
            tableName = table.name();
        }else{
            tableName = HumpUtils.humpToUnderLine(clazz.getName());
        }
        sql.SELECT("*").FROM(tableName);
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object fieldValue = field.get(obj);
            String dbFiledName = "";
            if (fieldValue != null) {
                //判断属性上面是否贴了Column注解，如果贴了则去Column的值作为数据库字段名，否则使用驼峰转换为下划线形式作为字段名
                Column column = field.getAnnotation(Column.class);
                if (column == null) {
                    dbFiledName = HumpUtils.humpToUnderLine(field.getName());
                } else {
                    dbFiledName = column.name();
                }
                sql.WHERE(String.format("%s=#{%s}", dbFiledName, field.getName()));
            }
        }
        return sql.toString();
    }
}
